<template>
    <div class="login-box" :style="changeLoginBgColor">
        <div class="i18n-box">
            <a-button type="primary" size="small" @click="testApi" style="margin-right:5px">测试api按钮</a-button>
            <a-button type="primary" size="small" @click="changeLang('zh')">中文</a-button>
            <a-button type="primary" size="small" @click="changeLang('en')" style="margin:5px 10px 0 10px">English</a-button>
            <a-popover placement="bottomRight" title="请选择背景色" trigger="click">
                <template #content>
                    <div class="bg-s" style="width:220px">
                        <a-tag class="bg-s-tag" style="margin-bottom: 10px;cursor: pointer;" 
                            v-for="(val,index) in bgColorList" 
                            :key="index"
                            :color="val" 
                            @click="changeBgColor(val)">
                            {{val}}
                        </a-tag>
                    </div>
                </template>
                <a-button type="primary" size="small" style="margin:0px 10px 0 0">点击切换皮肤</a-button>
            </a-popover>
        </div>
        <div class="login-page">
            <!-- 账号密码登录 -->
            <div class="form" v-if="loginHidden">
                <!-- action=/gatewayServer/userServeController/userLoginVerify 需要禁用表单的submit,否则button事件失效 -->
                <form class="login-form" onsubmit="return false">
                    <input type="text" v-model="loginForm.account" :placeholder="$t('loginForm.account')" />
                    <input type="password" v-model="loginForm.pwdCode" autocomplete :placeholder="$t('loginForm.password')"/>
                    <input type="text" v-model="loginForm.imgCode" :placeholder="$t('loginForm.imgcode')" style="width:62%;display:inline-block"/>
                    <img :src="formImg" @click="changeImgCode" style="width:102px;height:52px;margin-top: -4px;"/>
                    <button @click="clickLogin">{{$t('loginForm.loginBtn')}}</button>
                    <p class="message">
                        {{$t('loginForm.noAccount')}}? 
                        <a href="#" @click="ssmLoginCheck">{{$t('loginForm.smsLogin')}}</a> / 
                        <a href="#" @click="emailLoginCheck">{{$t('loginForm.emailLogin')}}</a>
                    </p>
                </form>
            </div>
            <!-- 短信登录 -->
            <div class="form" v-if="ssmHidden">
                <form class="login-form" onsubmit="return false">
                    <input type="text" v-model="loginForm.account" :placeholder="$t('loginForm.phoneNumber')"/>
                    <input type="number" v-model="loginForm.pwdCode" :placeholder="$t('loginForm.smsCode')"/>
                    <button style="margin-bottom:5px;height: 20px;line-height: 0px;" @click="preLoginCheck('2')">{{$t('loginForm.smsCodeBtn')}}</button>
                    <button @click="clickLogin">{{$t('loginForm.loginBtn')}}</button>
                    <p class="message">
                        <a href="#" @click="accountLoginCheck">{{$t('loginForm.accountLogin')}}</a> / 
                        <a href="#" @click="emailLoginCheck">{{$t('loginForm.emailLogin')}}</a>
                    </p>
                </form>
            </div>
            <!-- 邮箱登录 -->
            <div class="form" v-if="emailHidden">
                <form class="login-form" onsubmit="return false">
                    <input type="email" v-model="loginForm.account" :placeholder="$t('loginForm.emailAdd')"/>
                    <input type="text" v-model="loginForm.pwdCode" :placeholder="$t('loginForm.emailCode')"/>
                    <button style="margin-bottom:5px;height: 20px;line-height: 0px;" @click="preLoginCheck('3')">{{$t('loginForm.emailSendBtn')}}</button>
                    <button @click="clickLogin">{{$t('loginForm.loginBtn')}}</button>
                    <p class="message">
                        <a href="#" @click="accountLoginCheck">{{$t('loginForm.accountLogin')}}</a> / 
                        <a href="#" @click="ssmLoginCheck">{{$t('loginForm.emailLogin')}}</a>
                    </p>
                </form>
            </div>
        </div>
    </div>
</template>

<script>
import { reactive,toRefs,onMounted,computed } from "vue";
import { message } from "ant-design-vue";
import {$http} from '@/utils/axios';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n'
import {RSAencrypt} from './../../utils/RsaUtil'
export default {
    setup(){
        const { locale } = useI18n()
        const router = useRouter()
        onMounted(()=>{
            getImgCode()
        })
        let globalReactiveData = reactive({
            //账号密码登录表单
            "loginHidden":true,
            //短信登录表单
            "ssmHidden":false,
            //邮箱登录表单
            "emailHidden":false,
            "loginForm":{
                "account":"",
                "pwdCode":"",
                "imgCode":"",
                //登录类型,默认1:账号密码, 2:短信  3:邮箱
                "loginType":1,
            },
            "getSmsCodeOK":true,
            "smsLoginOK":false,
            "formImg":"",
            "preLogin":false,
            "bgColor":'rgb(141,194,111)',
            "bgColorList":['#FF6600','#2db7f5','#87d068','#108ee9','rgb(141,194,111)','#E6A23C','#67C23A','#F56C6C','#909399','#409EFF','#445CBB']
        });
        //国际化
        function changeLang(lang){
            console.log("i18n:",locale);
            locale.value = lang
            localStorage.setItem('lang', lang)// 重要！下面遇到问题里解释

        }
        //选择背景色
        function changeBgColor(color){
            globalReactiveData.bgColor = color
        }
        //换皮肤
        let changeLoginBgColor = computed(()=>{
            return `--bgColor:${globalReactiveData.bgColor};`
        })
        //账号密码登录
        const accountLoginCheck=(()=>{
            globalReactiveData.loginHidden=true
            globalReactiveData.ssmHidden=false
            globalReactiveData.emailHidden=false
            globalReactiveData.loginForm.account=''
            globalReactiveData.loginForm.pwdCode=''
            globalReactiveData.loginForm.imgCode=''
            globalReactiveData.loginForm.loginType=1
        })
        //邮箱登录
        function emailLoginCheck(){
            globalReactiveData.loginHidden=false
            globalReactiveData.ssmHidden=false
            globalReactiveData.emailHidden=true
            globalReactiveData.loginForm.account=''
            globalReactiveData.loginForm.pwdCode=''
            globalReactiveData.loginForm.imgCode=''
            globalReactiveData.loginForm.loginType=3
        }
        //短信登录
        function ssmLoginCheck(){
            globalReactiveData.loginHidden=false
            globalReactiveData.ssmHidden=true
            globalReactiveData.emailHidden=false
            globalReactiveData.loginForm.account=''
            globalReactiveData.loginForm.pwdCode=''
            globalReactiveData.loginForm.imgCode=''
            globalReactiveData.loginForm.loginType=2
        }
        /**
         * 表单校验方法 动态调用校验
         * @param {正则} reg 
         * @param {校验提示} regTip 
         * @param {用户名校验提示} accountTip 
         * @param {密码校验提示} pwdTip 
         */
        function loginDataValidata(reg,regTip,accountTip,pwdTip){
            if(globalReactiveData.loginForm.account===null || globalReactiveData.loginForm.account===''){
                message.warning(accountTip)
                return false
            }
            if(!reg.test(globalReactiveData.loginForm.account)){
                message.warning(regTip) 
                return false
            }

            if(globalReactiveData.loginForm.pwdCode===null || globalReactiveData.loginForm.pwdCode===''){
                message.warning(pwdTip)
                return false
            }
            return true
        }
        /**
         * 登录
         */
        const toLogin = () =>{
            let rsaEncrypyData = RSAencrypt('abcdsssss'.toString())
            $http.post("/gatewayServer/userServeController/userLoginVerify",globalReactiveData.loginForm).then((result)=>{
                if(result.data.code === "0000"){
                    sessionStorage.setItem("currentUser",JSON.stringify(result.data.data))
                    router.push("/index");
                    globalReactiveData.loginForm.account=''
                    globalReactiveData.loginForm.pwdCode=''
                    globalReactiveData.loginForm.imgCode=''
                    message.success("登录成功");
                }else{
                    getImgCode()
                    message.error(result.data.msg || "登录失败")
                }               
            }).catch((error)=>{
                console.log("登录异常:"+error)
                message.error("系统异常,登录失败")
            });         
        };
        /**
         * 预登录检验
         * 防止请求重复提交
         */
        function preLoginCheck(login){
            if(1===login){
                //在axios中设置请求头
                $http.post("/gatewayServer/userServeController/preLoginCheck").then((preRes)=>{
                    if(preRes.data.data){                   
                        toLogin()
                    }else{
                        message.warning("请勿重复提交,2s后再试!!!")
                    }
                })
            }else if(2===login){
                //在axios中设置请求头
                $http.post("/gatewayServer/userServeController/preLoginCheck").then((preRes)=>{
                    if(preRes.data.data){                   
                        sendSmsCode()
                    }else{
                        message.warning("请勿重复提交,2s后再试!!!")
                    }
                })
            }else{
                //在axios中设置请求头
                $http.post("/gatewayServer/userServeController/preLoginCheck").then((preRes)=>{
                    if(preRes.data.data){                   
                        sendEmailCode()
                    }else{
                        message.warning("请勿重复提交,2s后再试!!!")
                    }
                })
            }
            
        }
        //登录
        function clickLogin(){
            //校验           
            //账号登录
            if(globalReactiveData.loginHidden){
                let reg = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
                let regTip = '账号不合法:字母开头，允许5-16字节，允许字母数字下划线'
                if(!loginDataValidata(reg,regTip,'账户不能为空','密码不能为空')){
                    return
                }

                if(globalReactiveData.loginHidden && (globalReactiveData.loginForm.imgCode===null || globalReactiveData.loginForm.imgCode==='') ){
                    return message.warning('图片验证码不能为空')
                }
                //校验通过
                preLoginCheck(1)
                
            }
            //短信验证
            if(globalReactiveData.ssmHidden){
                let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
                let regTip = '请输入正确的手机号码'
                if(!loginDataValidata(reg,regTip,'手机号码不能为空','短信验证码不能为空')){
                    return
                }
                preLoginCheck(2)
            }
            //邮件验证
            if(globalReactiveData.emailHidden){
                let reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
                let regTip = '请输入正确的邮箱'
                if(!loginDataValidata(reg,regTip,'邮箱不能为空','邮箱验证码不能为空')){
                    return
                }
                preLoginCheck(3)
            }             
        }
        /**
         * 获取图片验证码
         */sendSmsCode
        function getImgCode(){
            globalReactiveData.formImg=$http.defaults.baseURL+'/gatewayServer/userServeController/getImageCode?d='+new Date();
        }

        /**
         * 更改图片验证码
         */
        function changeImgCode(){
            getImgCode();
        }
        // 获取短信验证码
        function sendSmsCode(){
            $http.get('/gatewayServer/userServeController/getSmsCodeByPhone?phone='+globalReactiveData.loginForm.account).then((res)=>{
                if(res.data.data){
                    message.success('发送成功')
                }else{
                    message.error(res.data.msg || '发送失败,请重新发送')
                }
            }).catch((err)=>{
                console.log("发送验证码:",err);
                message.error(err || '发送失败,请重新发送')
            })
        }
        // 获取邮箱验证码
        function sendEmailCode(){
            $http.get('/gatewayServer/userServeController/getEmailCodeByEmail?email='+globalReactiveData.loginForm.account).then((res)=>{
                if(res.data.data && res.data.code === '0000'){
                    message.success('发送成功')
                }else{
                    message.error(res.data.msg || '发送失败,请重新发送')
                }
            }).catch((err)=>{
                console.log("发送验证码:",err);
                message.error(err || '发送失败,请重新发送')
            })
        }

        //测试api
        function testApi(){
            $http.get("/gateway/testGateway3").then((res)=>{
                console.log('测试null:',res);
            })
        }
        

        return{
            ...toRefs(globalReactiveData),
            changeLoginBgColor,
            changeBgColor,
            accountLoginCheck,
            emailLoginCheck,
            ssmLoginCheck,
            clickLogin,
            preLoginCheck,
            changeImgCode,
            changeLang,
            sendSmsCode,
            sendEmailCode,
            testApi
        }
    }
}
</script>

<style scoped>
@import url(../../assets/css/LoginPageNew.css);
</style>